var menuManager_page = {};

menuManager_page.action = {
    initBody: function () {
        menuManager_page.interface.initTablePage();
        menuManager_page.action.bindEvent();
    },
    bindEvent: function () {
        $("#cancelBtn").click(function () {
            menuManager_page.action.initBody();
            return false;
        });
        $("#cancelBtn_add").click(function () {
            menuManager_page.action.initBody();
            return false;
        });
        $("#saveBtn").click(function () {
            var params = {
                id:$("#id").val(),
                menuKey:$("#menuKey").val(),
                menuName:$("#menuName").val(),
                parentId:$("#parentId").val(),
                comment:$("#comment").val(),
                target:$("#target").val(),
                orderId:$("#orderId").val(),
                level:$("#level").val(),
                href:$("#href").val()
            };
            menuManager_page.action.saveBtnClick("editSubmit", params);
        });
        $("#saveBtn_add").click(function () {
            var params = {
                id:$("#id").val(),
                menuKey:$("#menuKey_add").val(),
                menuName:$("#menuName_add").val(),
                parentId:$("#parentId_add").val(),
                comment:$("#comment_add").val(),
                target:$("#target_add").val(),
                orderId:$("#orderId_add").val(),
                level:$("#level_add").val(),
                href:$("#href_add").val()
            };
            menuManager_page.action.saveBtnClick("addSubmit", params);
        });

    },
    // 在做action动作时校验数据data
    checkData:function (action, data) {
        var result = AppComm.data.newResult();

        if((data.menuKey==""||data.menuKey==null||data.menuKey.trim()=="")){
            result.success = false;
            result.error = "菜单标识 不能为空。";
            return result;
        }

        var flag = 0;
        var params={
            menuKey:data.menuKey,
            id:data.id,
        };
        var onSuccess = function (resultData) {
            if (resultData.success) {
                if(resultData.data!=null){
                    flag++;
                }
            }
        };

        var checkUrl = "";
        if (action=='editSubmit') {
            checkUrl = AppComm.url.getBaseURL()+'/menuManager/ajax/getMenuListByMenuKeyOutCurrent';
        } else if (action=='addSubmit'){
            checkUrl = AppComm.url.getBaseURL()+'/menuManager/ajax/getMenuListByMenuKey';
        }

        AppComm.ajax.execute({
            'url':checkUrl,
            'data':params,
            'async':false,
            'success':onSuccess
        });

        if(flag>0){
            result.success = false;
            result.error = "该菜单标识已存在。";
        } else {
            result.success = true;
        }
        return result;
    },
    deleteMenu: function (id,level) {
        var params = {
            id: id,
            level:level
        };
        var onSuccess = function (resultData) {
            if (resultData.success) {
                layer.msg("删除成功！", {icon: 1});
                menuManager_page.interface.initTablePage();
            }
        };
        AppComm.ajax.execute({
            'url': AppComm.url.getBaseURL() + '/menuManager/ajax/deleteMenu',
            'data': params,
            'success': onSuccess
        });
    },
    saveBtnClick: function (active, params) {
        var result = menuManager_page.action.checkData(active, params);
        if (!result.success) {
            layer.alert(result.error, {
                icon: 0,
                skin: 'layer-ext-moon'
            })
        } else {
            var onSuccess = function (resultData) {
                if (resultData.success) {
                    menuManager_page.action.initBody();
                    layer.msg("保存成功！", {icon: 1});
                } else {
                    layer.msg("保存失败！", {icon: 2});
                }
            };
            AppComm.ajax.execute({
                'url':AppComm.url.getBaseURL()+'/menuManager/ajax/saveMenu',
                'data':params,
                'success':onSuccess
            });
        }
        return false;
    },
    saveBtn_addClick:function () {
        alert($("#comment_add").val());
        // var param={
        //     comment:$("#comment_add").val(),
        //     href:data.field.href_add,
        //     level:data.field.level_add,
        //     menuKey:data.field.menuKey_add,
        //     menuName:data.field.menuName_add,
        //     orderId:data.field.orderId_add,
        //     parentId:data.field.parentId_add,
        //     target: data.field.target_add,
        // };
        // var onSuccess = function (resultData) {
        //     if (resultData.success) {
        //         // menuManager_page.action.initBody();
        //         layer.msg("保存成功！");
        //         return;
        //     } else {
        //         layer.msg("保存失败！");
        //     }
        // };
        // AppComm.ajax.execute({
        //     'url':AppComm.url.getBaseURL()+'/menuManager/ajax/saveMenu',
        //     'data':param,
        //     'async':false,
        //     'success':onSuccess
        // });
    }
};
menuManager_page.interface = {
    // 加载表格页
    initTablePage: function () {
        menuManager_page.data.permissionEdit = false;
        if (AppComm.permission.hasPermission("menuManager:edit")) {
            menuManager_page.data.permissionEdit = true;
        }
        menuManager_page.data.permissionDelete = false;
        if (AppComm.permission.hasPermission("menuManager:delete")) {
            menuManager_page.data.permissionDelete = true;
        }

        var html = template("menuManagerList_template");
        $(".menuManager_box").html(html);
        
        var cols = [
            {field:'name', width:300, title: '菜单名称'},
            {field:'menuKey', width:300, title: '菜单关键字'},
            {field:'level', width:300, title: '等级'},
            {field:'url', width:300, title: '链接'},
            {field:'target', width:300, title: '打开方式'},
            {field:'orderId', width:300, title: '排序号'},
            {field:'comment', width:300, title: '说明'},
            {
                width:100,title: '操作', align:'center'/*toolbar: '#barDemo'*/
                ,templet: function(d){
                    var html='';
                    var editBtn='<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>';
                    var delBtn='<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>';
                    var addBtn='<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="add">添加</a>';
                    return addBtn+delBtn+addBtn;
                }
            }
        ];
        layui.config({
            base: '/static/comm/layui/lay/modules/',
        });
        // layui.extend({
        //     treeTable1: '{/}'+AppComm.url.getBaseURL()+'/static/comm/layui2.4.5/lay/modules/treeTable' // {/}的意思即代表采用自有路径，即不跟随 base 路径
        // });
        layui.use(['treeTable','layer','code','form'],function(){

            menuManager_page.data.permissionEdit = false;
            if (AppComm.permission.hasPermission("menuManager:edit")) {
                menuManager_page.data.permissionEdit = true;
            }
            menuManager_page.data.permissionDelete = false;
            if (AppComm.permission.hasPermission("menuManager:delete")) {
                menuManager_page.data.permissionDelete = true;
            }

            var o = layui.$,
                form = layui.form,
                layer = layui.layer,
                treeTable = layui.treeTable;
            // 直接下载后url: './data/table-tree.json',这个配置可能看不到数据，改为data:[],获取自己的实际链接返回json数组

            var onSuccess = function (resultData) {
                var	re = treeTable.render({
                    elem: '#tree-table',
                    // url: AppComm.url.getBaseURL() + '/menuManager/ajax/getMenuTreeTable',
                    // data:[{"id":"bdf688db90d541399def53c574f97134","parentId":"0","level":1,"target":"_self","comment":"","href":"","orderId":1.0,"menuKey":"manager","menuName":"系统配置"},{"id":"f400c04e7517489cbee1ad1bee83947f","parentId":"bdf688db90d541399def53c574f97134","level":2,"target":"_self","comment":"","href":"manager/menuManager","orderId":1.0,"menuKey":"manager_menu","menuName":"菜单配置"},{"id":"9e95e5431e1a4c7c90ebfdcd5d77bb68","parentId":"bdf688db90d541399def53c574f97134","level":2,"target":"_self","comment":"","href":"manager/userManager","orderId":2.0,"menuKey":"manager_userManager","menuName":"用户配置"},{"id":"02ab5766bd064ea6801e448e8d214236","parentId":"bdf688db90d541399def53c574f97134","level":2,"target":"_self","comment":"","href":"manager/roleManager","orderId":3.0,"menuKey":"manager_roleManager","menuName":"角色配置"},{"id":"d88ed07605174ecb940f064fd8131cc2","parentId":"bdf688db90d541399def53c574f97134","level":2,"target":"_self","comment":"","href":"manager/operationManager","orderId":4.0,"menuKey":"manager_operationManager","menuName":"操作配置"},{"id":"7c1061bcd1414d29b5c5f4db42a7b42b","parentId":"bdf688db90d541399def53c574f97134","level":2,"target":"_self","comment":"","href":"manager/groupManager","orderId":5.0,"menuKey":"manager_groupManager","menuName":"组织管理"},{"id":"f114ffa019804a0685950431f368b6a8","parentId":"bdf688db90d541399def53c574f97134","level":2,"target":"_self","comment":"","href":"manager/modifyPassword","orderId":6.0,"menuKey":"manager_modifyPassword","menuName":"修改密码"}],
                    // data: [{"id":1,"parentId":0,"menuName":"1-1"},{"id":2,"parentId":0,"menuName":"1-2"},{"id":3,"parentId":0,"menuName":"1-3"}],
                    data: resultData.data,
                    icon_key: 'menuName',
                    primary_key: 'id',
                    parent_key: 'parentId',
                    // is_checkbox: true,
                    // checked: {
                    //     key: 'id',
                    //     data: [0,1,4,10,11,5,2,6,7,3,8,9],
                    // },
                    end: function(e){
                        form.render();
                    },
                    cols: [
                        {
                            key: 'menuName',
                            title: '菜单名称',
                            width: '100px',
                            template: function(item){
                                if(item.level == 0){
                                    return '<span style="color:red;">'+item.menuName+'</span>';
                                }else if(item.level == 1){
                                    return '<span style="color:green;">'+item.menuName+'</span>';
                                }else if(item.level == 2){
                                    return '<span style="color:#aaa;">'+item.menuName+'</span>';
                                }
                            }
                        },
                        {
                            key: 'menuKey',
                            title: '菜单关键字',
                            width: '100px',
                            align: 'left',
                        },
                        {
                            key: 'level',
                            title: '等级',
                            width: '100px',
                            align: 'center',
                        },
                        {
                            key: 'href',
                            title: '链接',
                            width: '100px',
                            align: 'center',
                        },
                        {
                            key: 'target',
                            title: '打开方式',
                            width: '100px',
                            align: 'center',
                        },
                        {
                            key: 'orderId',
                            title: '排序号',
                            width: '100px',
                            align: 'center',
                        },
                        {
                            key: 'comment',
                            title: '说明',
                            width: '100px',
                            align: 'center',
                        },
                        {
                            title: '操作',
                            align: 'center',
                            template: function(item){

                                var renderHtml = '';

                                if (menuManager_page.data.permissionEdit) {
                                    renderHtml = renderHtml + '<a class="layui-btn layui-btn-xs editBtn" data-id='+item.id+'>编辑</a>';
                                }
                                if (menuManager_page.data.permissionDelete) {
                                    renderHtml = renderHtml + '<a class="layui-btn layui-btn-danger layui-btn-xs deleteBtn" data-id='+item.id+' data-level='+item.level+'>删除</a>';
                                }
                                return renderHtml;
                            }
                        }
                    ]
                });
            };
            AppComm.ajax.execute({
                'url':AppComm.url.getBaseURL()+'/menuManager/ajax/getMenuListByMenuKey',
                'data':'',
                'async':false,
                'success':onSuccess
            });

            $(".editBtn").click(function () {
                menuManager_page.interface.initFormPage($(this).attr("data-id"));
            });
            $(".deleteBtn").click(function () {
                var id = $(this).attr("data-id");
                var level = $(this).attr("data-level");
                layer.confirm('确定要进行删除吗？',{icon: 3, title:'提示'},function(index){
                    menuManager_page.action.deleteMenu(id,level);
                    layer.close(index);
                }, function(index){
                    layer.close(index);
                });
            });
            $("#addBtn").click(function () {
                menuManager_page.interface.initFormPage();
                menuManager_page.action.bindEvent();
                return false;
            });
        })

            },
    // 初始化表单页
    initFormPage: function (dataId) {
        if (dataId == undefined || '' == dataId.trim()) {
            // 添加
            var onSuccess1 = function (resultData) {
                layer.closeAll('loading');
                var html = template("menuManagerForm_template_add", resultData.data);
                $(".menuManager_box").html(html);
                $("#href_div").hide();
                $("input#href_add").val("");
                menuManager_page.action.bindEvent();
                layui.use('form', function(){
                    var form = layui.form;
                    form.render();
                    form.on('select(level)', function(data){
                        if(data.value=="1"){
                            $("#parentId_div").html("");
                            var html = "<select id='parentId_add' name='parentId_add' lay-verify='required' lay-search='' lay-filter='parentId'>"
                                        +"<option value='0'>主菜单</option>"
                                        +"</select>";
                            $("#parentId_div").append(html);
                            $("#href_div").hide();
                            $("input#href_add").val("");
                        }
                        if(data.value=="2"){
                            $("#parentId_div").html("");
                            var option;
                            for(var i=0;i<resultData.data.parentList.length;i++){
                                option = option+"<option value='"+resultData.data.parentList[i].id+"'>"+resultData.data.parentList[i].menuName+"</option>"
                            }
                            var html = "<select id='parentId_add' name='parentId_add' lay-verify='required' lay-search='' lay-filter='parentId'>"
                                +option
                                +"</select>";
                            $("#parentId_div").append(html);
                            $("#href_div").show();
                        }
                        form.render();
                    });
                    // form.verify({
                    //     menuKey_add:function(value){
                    //         if((value==""||value==null)){
                    //             return "菜单关键字不能为空";
                    //         }
                    //         var flag = 0;
                    //         var params={
                    //             menuKey:value,
                    //         };
                    //         var onSuccess = function (resultData) {
                    //             if (resultData.success) {
                    //                 if(resultData.data && resultData.data.length>0){
                    //                     flag++;
                    //                 }
                    //             }
                    //         };
                    //         AppComm.ajax.execute({
                    //             'url':AppComm.url.getBaseURL()+'/menuManager/ajax/getMenuListByMenuKey',
                    //             'data':params,
                    //             'async':false,
                    //             'success':onSuccess
                    //         });
                    //         if(flag>0){
                    //             return "菜单关键字不能重复";
                    //         }
                    //     },
                    // });


                    // form.on('submit(saveBtn_add)', function(data){
                        // var param={
                        //     comment:data.field.comment_add,
                        //     href:data.field.href_add,
                        //     level:data.field.level_add,
                        //     menuKey:data.field.menuKey_add,
                        //     menuName:data.field.menuName_add,
                        //     orderId:data.field.orderId_add,
                        //     parentId:data.field.parentId_add,
                        //     target: data.field.target_add,
                        // };
                        // var onSuccess = function (resultData) {
                        //     if (resultData.success) {
                        //         // menuManager_page.action.initBody();
                        //         layer.msg("保存成功！");
                        //         return;
                        //     } else {
                        //         layer.msg("保存失败！");
                        //     }
                        // };
                        // AppComm.ajax.execute({
                        //     'url':AppComm.url.getBaseURL()+'/menuManager/ajax/saveMenu',
                        //     'data':param,
                        //     'async':false,
                        //     'success':onSuccess
                        // });
                    // });
                });
            };

            AppComm.ajax.execute({
                'url': AppComm.url.getBaseURL() + '/menuManager/ajax/addMenuInfoById',
                'data': params,
                'success': onSuccess1
            });

        } else {
            // 编辑
            layer.load();
            var params = {
                id: dataId
            };
            var onSuccess = function (resultData) {
                layer.closeAll('loading');
                var html = template("menuManagerForm_template", resultData.data);
                $(".menuManager_box").html(html);
                if(resultData.data.menuBo.level=="1"){
                    $("#href_edit").hide();
                    $("input#href").val("");
                }
                menuManager_page.action.bindEvent();
                layui.use('form', function(){
                    var form = layui.form;
                    form.render();
                    form.on('select(level_edit)', function(data){
                        if(data.value=="1"){
                            $("#parentId_edit").html("");
                            var html = "<select id='parentId_add' name='parentId_add' lay-verify='required' lay-search=''>"
                                +"<option value='0'>主菜单</option>"
                                +"</select>";
                            $("#parentId_edit").append(html);
                            $("#href_edit").hide();
                            $("input#href").val("");
                        }
                        if(data.value=="2"){
                            $("#parentId_edit").html("");
                            var option;
                            for(var i=0;i<resultData.data.parentList.length;i++){
                                option = option+"<option value='"+resultData.data.parentList[i].id+"'>"+resultData.data.parentList[i].menuName+"</option>"
                            }
                            var html = "<select id='parentId' name='parentId' lay-verify='required' lay-search=''>"
                                +option
                                +"</select>";
                            $("#parentId_edit").append(html);
                            $("#href_edit").show();
                        }
                        form.render();
                    });
                    // form.verify({
                    //     menuKey:function(value){
                    //         var flag = 0;
                    //         var params={
                    //             menuKey:value,
                    //             id:dataId,
                    //         };
                    //         var onSuccess = function (resultData) {
                    //             if (resultData.success) {
                    //                 if(resultData.data!=null){
                    //                     flag++;
                    //                 }
                    //             }
                    //         };
                    //         AppComm.ajax.execute({
                    //             'url':AppComm.url.getBaseURL()+'/menuManager/ajax/getMenuListByMenuKeyOutCurrent',
                    //             'data':params,
                    //             'async':false,
                    //             'success':onSuccess
                    //         });
                    //         if(flag>0){
                    //             return "菜单关键字不能重复";
                    //         }
                    //     },
                    // });
                    // form.on('submit(saveBtn)', function(data){
                        //     data.field.id = dataId;
                        // var onSuccess = function (resultData) {
                        //     if (resultData.success) {
                        //         // menuManager_page.action.initBody();
                        //         layer.msg("保存成功！");
                        //         return;
                        //     } else {
                        //         layer.msg("保存失败！");
                        //     }
                        // };
                        // AppComm.ajax.execute({
                        //     'url':AppComm.url.getBaseURL()+'/menuManager/ajax/saveMenu',
                        //     'data':data.field,
                        //     'async':false,
                        //     'success':onSuccess
                        // });
                    // });
                });
            };
            AppComm.ajax.execute({
                'url': AppComm.url.getBaseURL() + '/menuManager/ajax/getMenuInfoById',
                'data': params,
                'success': onSuccess
            });
        }
    },
};

menuManager_page.data = {
    'tableIns': undefined,
    'permissionEdit':false,
    'permissionDelete':false,
    'action':""
};

AppComm.initFrame(menuManager_page);